/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.mes.rest;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.mes.domain.MesTemplateConfig;
import me.zhengjie.modules.mes.domain.vo.MesTemplateConfigData;
import me.zhengjie.modules.mes.domain.vo.MesTemplateConfigQueryCriteria;
import me.zhengjie.modules.mes.excel.MesTemplateConfigListener;
import me.zhengjie.modules.mes.service.MesTemplateConfigService;
import me.zhengjie.service.MinioService;
import me.zhengjie.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* @author mfc
* @date 2024-12-25
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "MesTemplateConfig管理")
@RequestMapping("/api/mesTemplateConfig")
public class MesTemplateConfigController {

    private final MesTemplateConfigService mesTemplateConfigService;

    @Autowired
    private MinioService minioService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('mesTemplateConfig:list')")
    public void exportMesTemplateConfig(HttpServletResponse response, MesTemplateConfigQueryCriteria criteria) throws IOException {
        mesTemplateConfigService.download(mesTemplateConfigService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询MesTemplateConfig")
    @ApiOperation("查询MesTemplateConfig")
    @PreAuthorize("@el.check('mesTemplateConfig:list')")
    public ResponseEntity<PageResult<MesTemplateConfig>> queryMesTemplateConfig(MesTemplateConfigQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(mesTemplateConfigService.queryAll(criteria,page),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增MesTemplateConfig")
    @ApiOperation("新增MesTemplateConfig")
    @PreAuthorize("@el.check('mesTemplateConfig:add')")
    public ResponseEntity<Object> createMesTemplateConfig(@Validated @RequestBody MesTemplateConfig resources){
        mesTemplateConfigService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改MesTemplateConfig")
    @ApiOperation("修改MesTemplateConfig")
    @PreAuthorize("@el.check('mesTemplateConfig:edit')")
    public ResponseEntity<Object> updateMesTemplateConfig(@Validated @RequestBody MesTemplateConfig resources){
        mesTemplateConfigService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除MesTemplateConfig")
    @ApiOperation("删除MesTemplateConfig")
    @PreAuthorize("@el.check('mesTemplateConfig:del')")
    public ResponseEntity<Object> deleteMesTemplateConfig(@RequestBody List<Integer> ids) {
        mesTemplateConfigService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    @PostMapping("/upload")
    @Log("上传模版配置")
    @ApiOperation("上传模版配置")
    public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("templatePageEn") String templatePageEn, @RequestParam("targetFunctionId1") int targetFunctionId1, @RequestParam("targetFunctionId2") int targetFunctionId2, @RequestParam("targetFunctionId3") int targetFunctionId3) {
        try {
            String url = minioService.uploadFile(file);
            //读取excel模板,写入表
            MesTemplateConfigListener listener = new MesTemplateConfigListener();
            EasyExcel.read(file.getInputStream(), MesTemplateConfigData.class, listener).sheet().doRead();
            List<MesTemplateConfigData> datas = listener.getDatas();
            List<MesTemplateConfig> mesTemplateConfigs = new ArrayList<>();
            for (MesTemplateConfigData data : datas) {
                MesTemplateConfig mesTemplateConfig = new MesTemplateConfig();
                mesTemplateConfig.setTemplatePage(templatePageEn);
                mesTemplateConfig.setTemplatePageEn(templatePageEn);
                mesTemplateConfig.setComponentName(data.getComponentName());
                mesTemplateConfig.setComponentNameEn(data.getComponentNameEn());
                mesTemplateConfig.setControlName(data.getControlName());
                mesTemplateConfig.setControlNameEn(data.getControlNameEn());
                mesTemplateConfig.setContentControlKey(data.getContentControlKey());
                mesTemplateConfig.setContentControl(data.getContentControl());
                mesTemplateConfig.setContentColor(data.getContentColor());
                mesTemplateConfig.setContentColorKey(data.getContentColorKey());
                mesTemplateConfig.setFromField(data.getFromField());
                mesTemplateConfig.setFromTable(data.getFromTable());
                mesTemplateConfig.setSort(data.getSort());
                mesTemplateConfig.setSortKey(data.getSortKey());
                mesTemplateConfig.setTagKey(data.getTagKey());
                mesTemplateConfig.setTagLabel(data.getTagLabel());
                mesTemplateConfig.setComponentName(data.getComponentName());
                mesTemplateConfig.setTargetFunctionId1(targetFunctionId1);
                mesTemplateConfig.setTargetFunctionId2(targetFunctionId2);
                mesTemplateConfig.setTargetFunctionId3(targetFunctionId3);
                mesTemplateConfigs.add(mesTemplateConfig);

            }
            mesTemplateConfigService.deleteByfunctionId(targetFunctionId1, targetFunctionId2, targetFunctionId3);
            mesTemplateConfigService.saveBatch(mesTemplateConfigs);
            return new ResponseEntity<>(url,HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to upload file: " + e.getMessage());
        }
    }

    @GetMapping("/queryByComponentNameEn")
    @Log("根据组件查询")
    @ApiOperation("根据组件查询")
    @PreAuthorize("@el.check('mesTemplateConfig:list')")
    public ResponseEntity<List<MesTemplateConfig>> queryByComponentNameEn(MesTemplateConfigQueryCriteria criteria){
        return new ResponseEntity<>(mesTemplateConfigService.queryAll(criteria),HttpStatus.OK);
    }
}